package com.shqcjd.preinstallmobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.ui.activity.remote.PushVideoCallActivity;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.DateUtil;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;
import com.shqcjd.preinstallmobile.widget.BlurTransformation;
import com.shqcjd.preinstallmobile.widget.WaveView;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

/**
 * 等待接听
 */
public class WaitingAnswerActivity extends BaseActivity {

    @BindView(R.id.iv_bg_img)
    ImageView ivBgImg;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.wv_icon_bg)
    WaveView wvIconBg;
    @BindView(R.id.civ_icon)
    CircleImageView civIcon;
    @BindView(R.id.fl_close_btn)
    FrameLayout flCloseBtn;
    private AgoraAPIOnlySignal mAgoraAPI;
    private Context mContext;
    private int remoteId;
    private String channeName;
    private int equipmentId;
    private int taskId;
    private String icon;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_waiting_answer;
    }

    @Override
    public void initView() {
        mContext = this;
        initAgoraEngineAndJoinChannel();
        remoteId = getIntent().getIntExtra("remoteId", -1);
        equipmentId = getIntent().getIntExtra("equipmentId", -1);
        taskId = getIntent().getIntExtra("taskId", -1);
        icon = getIntent().getStringExtra("icon");

        initIcon();
        long curTimeLong = DateUtil.getCurTimeLong();
        channeName = "yuhuan@"+curTimeLong;
        //查询对方是否在线
        mAgoraAPI.queryUserStatus(remoteId + "");

    }

    private void initIcon() {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_default_tx)    //加载成功之前占位图
                .error(R.mipmap.ic_default_tx) ;   //加载错误之后的错误图
//                .override(57, 57);//指定图片的缩放类型为centerCrop （等比例缩放图片，直到图片的宽高都
        Glide.with(this)
                .load(icon)
                .apply(options)
                .into(civIcon);

        // 高斯模糊
        Glide.with(this)
                .load(icon)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(this,20, 6)))
                .into(ivBgImg);

        //水波纹效果
        wvIconBg.setDuration(5000);
        wvIconBg.setStyle(Paint.Style.FILL);
        wvIconBg.setSpeed(1000);
        wvIconBg.setColor(ContextCompat.getColor(this,R.color.white));
        wvIconBg.setInterpolator(new LinearOutSlowInInterpolator());
        wvIconBg.setMaxRadius(UIUtils.dp2px(123));
        wvIconBg.start();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

            }
        },3000);
    }


    private void initAgoraEngineAndJoinChannel() {
        mAgoraAPI = MyApp.the().getmAgoraAPI();
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallback();

    }

    @OnClick(R.id.fl_close_btn)
    public void onViewClicked() {
        //取消呼叫
        mAgoraAPI.channelInviteEnd(channeName, remoteId + "", 0);
        finish();
    }

    private void addCallback() {
        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            Logger.i("其他登录帐户，你注销了");

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            Logger.i("注销网络不能");

                        }
                        finish();
                    }
                });

            }

            @Override
            public void onLoginFailed(int i) {
                Logger.i("onLoginFailed  i = " + i);
            }


            //当呼叫被对方收到时触发。，本地将回调 onInviteReceivedByPeer, 对方会回调 onInviteReceived。
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver


            }

            //当呼叫被对方接受时触发此回调。
            @Override
            public void onInviteAcceptedByPeer(String channelID, final String account, int uid, String extra) {
                super.onInviteAcceptedByPeer(channelID, account, uid, extra);
                Intent intent = new Intent(WaitingAnswerActivity.this, PushVideoCallActivity.class);
                intent.putExtra("channelID", channelID);
                intent.putExtra("expertID", account);
                intent.putExtra("equipmentId", equipmentId);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                finish();

            }

            //当呼叫被对方拒绝时触发此回调
            @Override
            public void onInviteRefusedByPeer(String channelID, String account, int uid, String extra) {
                super.onInviteRefusedByPeer(channelID, account, uid, extra);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort(mContext,"对方拒绝通话");
                        finish();
                    }
                });

            }

            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Logger.i("onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Logger.i("onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Logger.i(s1);
                        }
                    }
                });
            }

            //用户状态查询回调 (onQueryUserStatusResult) 1: 用户在线 0: 用户离线
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Logger.i("onQueryUserStatusResult name:"+name+" status:"+status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (status.equals("1")) {
                            //加入指导频道
                            mAgoraAPI.channelJoin(channeName);
                        } else if (status.equals("0")) {
                            ToastUtils.showShort(mContext,"对方离线状态");
                            finish();
                        }
                    }
                });
            }

            //结束呼叫 本端会回调 onInviteEndByMyself，对端会回调 onInviteEndByPeer
            @Override
            public void onInviteEndByMyself(String channelID, String account, int uid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            /**
             * 加入信令频道成功
             * @param channelID
             */
            @Override
            public void onChannelJoined(String channelID) {
                super.onChannelJoined(channelID);
                Logger.e("加入成功: 房间号:" + channelID);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                            //发起呼叫   成功：自己收到 ICallBack 类的 onInviteAcceptedByPeer() 回调
                            mAgoraAPI.channelInviteUser2(channelID, remoteId + "", null);

                    }
                });
            }
        });
    }
}
